﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using Otgruzka.ServicesClients;
using BusinessLogic.Security;
using Otgruzka.Controls.jQuery;
using Common.Util;
using System.Collections.Generic;
using Common.Export;
using System.Windows;
using System.Windows.Media;
using Otgruzka.Export;
using Otgruzka.Helpers;
using DataTier;
using DataTier.Entities;
using System.ServiceModel;

namespace Otgruzka.Controls.Product
{
    public partial class ProductEdit : System.Web.UI.UserControl
    {
        /// <summary>
        /// Свойство, указывающее на наличие фильтра
        /// </summary>
        protected bool IsFiltered
        {
            get { return Session["SearchParameters"] != null && Session["SearchParameters"] is SearchParameters; }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            SearchParameters searchParameters = new SearchParameters();

            if (IsPostBack)
            {
                // Заполняется объект SearchParameters
                searchParameters = GetSearchParameters();
            }
            else
            {
                searchParameters.ProductVisibleState = rbVisibleState.visibled;
                
                MeasureUnitsBind(this.ddlNewProdMeasureUnits); // Заполняется выпадающий список единиц измерений
            }
            // SearchParameters добавляется в сессию
            Session["SearchParameters"] = searchParameters;
            
            BindPaging(searchParameters);
            if (!IsPostBack)
                BindData();
            FillFiltersFields();
        }


        protected void HIsHiddenFilterRBL_Load(object sender, EventArgs e)
        {
            var searchParameters = GetSearchParameters();
            if (searchParameters == null)
            {
                searchParameters = new SearchParameters();
                searchParameters.ProductVisibleState = rbVisibleState.visibled;
                Session["SearchParameters"] = searchParameters;
            }
            if (string.IsNullOrEmpty(searchParameters.ProductVisibleState) )
            {
                searchParameters.ProductVisibleState = rbVisibleState.visibled;
                Session["SearchParameters"] = searchParameters;
            }
            if ((sender as RadioButtonList).SelectedValue != searchParameters.ProductVisibleState)
                (sender as RadioButtonList).SelectedValue = searchParameters.ProductVisibleState;

            (sender as RadioButtonList).SelectedItem.Attributes.Add("class", "selectedradio");
        }

        protected void HIsHiddenFilterRBL_SelectedIndexChanged(object sender, EventArgs e)
        {
            (sender as RadioButtonList).SelectedItem.Attributes.Add("class", "selectedradio");
            BindAndFillFiltersPaging();
        }

        //protected void Page_PreRender(object sender, EventArgs e)
        //{
        //    BindData();
        //}


        private void BindPaging(SearchParameters searchParameters)
        {
            int? numRows = new ProductsClient().GetProductListCount(UserPrincipal.Current.UserId, searchParameters);
            this.PagingTop.CountRows = numRows;
            this.PagingTop.NumPageSessionName = "productsNumPage";
            this.PagingTop.PageNumberChange += new Paging.PageNumberChangeHandler(PagingTop_PageNumberChange);

            this.PagingBottom.CountRows = numRows;
            this.PagingBottom.NumPageSessionName = "productsNumPage";
            this.PagingBottom.PageNumberChange += new Paging.PageNumberChangeHandler(PagingBottom_PageNumberChange);
        }

        void PagingBottom_PageNumberChange(object sender, PageNumberChangeEventArgs data)
        {
            this.PagingTop.Bind();
            BindData();
            FillFiltersFields(); // Заполняются поля ввода для фильтров из Session
        }

        void PagingTop_PageNumberChange(object sender, PageNumberChangeEventArgs data)
        {
            this.PagingBottom.Bind();
            BindData();
            FillFiltersFields(); // Заполняются поля ввода для фильтров из Session
        }


        /// <summary>
        /// Заполняются поля ввода для фильтров из Session
        /// </summary>
        private void FillFiltersFields()
        {
            var searchParameters = Session["SearchParameters"] as SearchParameters;
            if (searchParameters != null)
            {
                #region Заполняются поля ввода фильтров

                var HArtikul = this.gvMaster.HeaderRow.FindControl("HArtikul") as TextBox;
                var HProductName = this.gvMaster.HeaderRow.FindControl("HProductName") as TextBox;
                var HSupplierName = this.gvMaster.HeaderRow.FindControl("HSupplierName") as TextBox;
                var HSupplierArtikul = this.gvMaster.HeaderRow.FindControl("HSupplierArtikul") as TextBox;
                var HProductId = this.gvMaster.HeaderRow.FindControl("HProductId") as TextBox;
                var HIsHiddenFilterRBL = this.gvMaster.HeaderRow.FindControl("HIsHiddenFilterRBL") as RadioButtonList;

                if (HProductName != null)
                    HProductName.Text = searchParameters.ProductName;

                if (HArtikul != null)
                    HArtikul.Text = searchParameters.ProductArtikul;

                if (HSupplierName != null)
                    HSupplierName.Text = searchParameters.ProductSupplierName;

                if (HSupplierArtikul != null)
                    HSupplierArtikul.Text = searchParameters.ProductSupplierArtikul;

                if (HProductId != null)
                    HProductId.Text = (searchParameters.ProductId.HasValue) ? searchParameters.ProductId.ToString() : "";

                if (HIsHiddenFilterRBL != null)
                    HIsHiddenFilterRBL.SelectedValue = (!string.IsNullOrEmpty(searchParameters.ProductVisibleState)) ? searchParameters.ProductVisibleState : rbVisibleState.visibled;

                #endregion Заполняются поля ввода фильтров
            }
        }


        /// <summary>
        /// Возвращается объект SearchParameters формирующийся из полей ввода фильтров
        /// </summary>
        /// <returns></returns>
        private SearchParameters GetSearchParameters()
        {
            // Создаем экземпляр SearchParameters
            SearchParameters searchParameters = new SearchParameters();

            #region Заполняется объект SearchParameters

            var HArtikul = this.gvMaster.HeaderRow.FindControl("HArtikul") as TextBox;
            var HProductName = this.gvMaster.HeaderRow.FindControl("HProductName") as TextBox;
            var HSupplierName = this.gvMaster.HeaderRow.FindControl("HSupplierName") as TextBox;
            var HSupplierArtikul = this.gvMaster.HeaderRow.FindControl("HSupplierArtikul") as TextBox;
            var HProductId = this.gvMaster.HeaderRow.FindControl("HProductId") as TextBox;
            var HIsHiddenFilterRBL = this.gvMaster.HeaderRow.FindControl("HIsHiddenFilterRBL") as RadioButtonList;

            if (HArtikul != null && !string.IsNullOrEmpty(HArtikul.Text))
                searchParameters.ProductArtikul = HArtikul.Text;

            if (HProductName != null && !string.IsNullOrEmpty(HProductName.Text))
                searchParameters.ProductName = HProductName.Text;

            if (HSupplierName != null && !string.IsNullOrEmpty(HSupplierName.Text))
                searchParameters.ProductSupplierName = HSupplierName.Text;

            if (HSupplierArtikul != null && !string.IsNullOrEmpty(HSupplierArtikul.Text))
                searchParameters.ProductSupplierArtikul = HSupplierArtikul.Text;

            if (HProductId != null && !string.IsNullOrEmpty(HProductId.Text))
            {
                try
                {
                    searchParameters.ProductId = Convert.ToInt32(HProductId.Text);
                }
                catch { }
            }

            if (HIsHiddenFilterRBL != null && HIsHiddenFilterRBL.SelectedItem != null)
                searchParameters.ProductVisibleState = HIsHiddenFilterRBL.SelectedValue;
            


            // Если все поля с фильтрами пустые, то объект с параметрами приравнивается NULL
            if ((HArtikul == null || string.IsNullOrEmpty(HArtikul.Text)) &&
                (HProductName == null || string.IsNullOrEmpty(HProductName.Text)) &&
                (HSupplierArtikul == null || string.IsNullOrEmpty(HSupplierArtikul.Text)) &&
                (HSupplierName == null || string.IsNullOrEmpty(HSupplierName.Text)) &&
                (HProductId == null || string.IsNullOrEmpty(HProductId.Text)) &&
                (HIsHiddenFilterRBL == null || HIsHiddenFilterRBL.SelectedItem == null)
            )
            {
                searchParameters = null;// (Session["SearchParameters"] != null) ? Session["SearchParameters"] as SearchParameters : null;
            }

            #endregion Заполняется объект SearchParameters
            
            return searchParameters;
        }


        protected void ProductList_Filtr_click(object sender, EventArgs e)
        {
            // Заполняются поля ввода для фильтров из Session
            //SearchParameters searchParameters = null;
            //searchParameters = GetSearchParameters();
            //BindPaging(searchParameters);
            //BindData();
            //FillFiltersFields();
            this.PagingTop.CurrentPageNumber = 1;
            this.PagingBottom.CurrentPageNumber = 1;
            BindAndFillFiltersPaging();
        }


        protected void updateButton_Click(object sender, EventArgs e)
        {
            //BindData();
            BindAndFillFiltersPaging();
        }


        protected void btnAddNewProd_click(object sender, EventArgs e)
        {
            string name = this.NewProdName.Text;
            string artikul = this.NewProdArtikul.Text;
            string price = this.NewProdPrice.Text;
            string supplierArtikul = this.NewProdSupplierArtikul.Text;
            string supplierName = this.NewProdSupplierName.Text;
            int measureUnitId = Convert.ToInt32(this.ddlNewProdMeasureUnits.SelectedItem.Value);

            if (string.IsNullOrEmpty(name) && string.IsNullOrEmpty(artikul) && string.IsNullOrEmpty(price) && string.IsNullOrEmpty(supplierArtikul) && string.IsNullOrEmpty(supplierName))
                return;

            var client = new ProductsClient();

            var measureUnit = client.GetMeasureUnitById(UserPrincipal.Current.UserId, measureUnitId);
            if (measureUnit == null)
                measureUnit = client.GetMeasureUnitById(UserPrincipal.Current.UserId, Convert.ToInt32(ConfigurationManager.AppSettings["DefaultMeasureUnitId"]));

            try
            {
                ProductEntity product = new ProductEntity()
                {
                    Product = new DataTier.Product()
                    {
                        IsUnavailable = false,
                        ProductName = name,
                        Artikul = artikul,
                        Price = (!string.IsNullOrEmpty(price)) ? price.GetDoubleFromString() : (double?)null,
                        SupplierArtikul = supplierArtikul,
                        SupplierName = supplierName
                    },
                    // TODO: Сделать заполнение значения Единицы измерения
                    MeasureUnit = measureUnit
                };

                int id = client.SaveProduct(UserPrincipal.Current.UserId, product);

                #region Добавление информации о фотографии к уже сохраненному товару
                if (this.NewProdImage.HasFile)
                {
                    string pathToSaveBigImage = Server.MapPath("~/Images/products/big/");
                    string pathToSaveSmallImage = Server.MapPath("~/Images/products/small/");
                    string imgBig = pathToSaveBigImage;
                    string imgSmall = pathToSaveSmallImage;

                    // Выбирается расширение файла
                    string ext = (this.NewProdImage.FileName.Length >= this.NewProdImage.FileName.LastIndexOf('.')) ? this.NewProdImage.FileName.Substring(this.NewProdImage.FileName.LastIndexOf('.')) : "";

                    // Сохраняется BIG-версия файла, т.е. файл в исходном состоянии
                    this.NewProdImage.PostedFile.SaveAs(imgBig + string.Format("{0}_big{1}", id, ext));

                    // Сохраняется SMALL-версия файла, т.е. миниатюра
                    //this.NewProdImage.PostedFile.SaveAs(imgSmall + string.Format("{0}_small{1}", id, ext));
                    var img = GraphicHelper.ScaleByPercent(System.Drawing.Image.FromStream(this.NewProdImage.FileContent));
                    img.Save(imgSmall + string.Format("{0}_small{1}", id, ext));

                    // Формируются строки с путями к файлам для записи их в БД
                    imgBig = "/Images/products/big/" + string.Format("{0}_big{1}", id, ext);
                    imgSmall = "/Images/products/small/" + string.Format("{0}_small{1}", id, ext);

                    client.UpdateImageProduct(UserPrincipal.Current.UserId, id, imgBig, imgSmall);
                }
                #endregion Добавление информации о фотографии к уже сохраненному товару

                Response.Redirect("~/Admin/Products.aspx", true);
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
            }
            catch (System.Exception exp)
            {
                this.ErrorMessage.Text = exp.Message;
            }
        }

        private void MeasureUnitsBind(DropDownList ddlMeasureUnits)
        {
            var client = new ProductsClient();
            try
            {
                var list = client.GetMeasureUnitList(UserPrincipal.Current.UserId);
                ddlMeasureUnits.DataSource = list;
                ddlMeasureUnits.DataBind();
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
            }
            catch (System.Exception exp)
            {
                this.ErrorMessage.Text = exp.Message;
            }
        }


        #region Блок кода для NestedGridView

        protected void gvMaster_PreRender(object sender, EventArgs e)
        {
            //var hArtikul = this.gvMaster.HeaderRow.FindControl("HArtikul") as TextBox;
            //if (hArtikul != null)
            //    hArtikul.Attributes.Add("onkeypress", "return filter_keypress(event);");
            ////this.HArtikul.Attributes.Add("onkeypress", "filter_keypress(event);return false;");
            

            //foreach (GridViewRow row in gvMaster.Rows)
            //{
            //    ImageButton img = (ImageButton)row.FindControl("imgButSel");
            //    GridView gv = (GridView)row.FindControl("gvChild");
            //    SqlDataSource dsChild = (SqlDataSource)row.FindControl("dsChild");
            //    if (dsChild != null)
            //        dsChild.SelectParameters[0].DefaultValue = row.Cells[3].Text;

            //    if (gv != null)
            //    {
            //        if (!gv.Visible)
            //        {
            //            if (img != null)
            //                img.ImageUrl = "~/images/noselect.gif";
            //        }
            //        else
            //        {
            //            BindChildData(gv);
            //            if (img != null)
            //                img.ImageUrl = "~/images/select.gif";
            //        }
            //    }
            //}
        }
        protected void gvMaster_SearchGrid(object sender, string _strSearch)
        {
            if (_strSearch != null && _strSearch.ToUpper().StartsWith("CATEGORYID "))
                _hfSearch.Value = _strSearch.ToUpper().Replace("CATEGORYID ", "Convert(CATEGORYID, 'System.String') ");
            else
                _hfSearch.Value = _strSearch;
            BindData();
        }
        
        void BindData()
        {
            var client = new ProductsClient();
            try
            {
                string sortDirection = (ViewState["ProductList_SortDirection"] != null) ? ViewState["ProductList_SortDirection"] as string : "";
                string sortColumn = (ViewState["ProductList_SortExpression"] != null) ? ViewState["ProductList_SortExpression"] as string : "";

                int numPage = this.PagingTop.CurrentPageNumber;
                int onPage = (ConfigurationManager.AppSettings["RowsOnPage"] != null) ? Convert.ToInt32(ConfigurationManager.AppSettings["RowsOnPage"]) : 11;

                var searchParameters = (Session["SearchParameters"] != null) ? Session["SearchParameters"] as SearchParameters : null;

                var list = client.GetProductList(UserPrincipal.Current.UserId, numPage, onPage, searchParameters, sortColumn, sortDirection);
                if (list == null || list.Count == 0)
                {
                    list = new List<ProductEntity>();
                    list.Add(new ProductEntity());

                    this.gvMaster.DataSource = list;
                    this.gvMaster.DataBind();
                    this.gvMaster.Rows[0].Visible = false;
                }
                else
                {
                    this.gvMaster.DataSource = list;
                    this.gvMaster.DataBind();
                }

                //dsMaster.FilterExpression = _hfSearch.Value;
                //dsMaster.Select(new DataSourceSelectArguments());
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
            }
            catch (System.Exception exp)
            {
                this.ErrorMessage.Text = exp.Message;
            }
        }


        protected void HeaderColumn_Click(object sender, EventArgs e)
        {
            var button = sender as LinkButton;
            if (button != null && button.CommandName.Equals("Sort"))
            {
                string column = button.CommandArgument.ToString();
                string direction = GetSortDirection(column);
                //Sorting(column, direction);

                SearchParameters searchParameters = null;
                searchParameters = GetSearchParameters();
                BindPaging(searchParameters);
                BindData();
                FillFiltersFields();
            }
        }

        private string GetSortDirection(string column)
        {

            // By default, set the sort direction to ascending.
            string sortDirection = "ASC";

            // Retrieve the last column that was sorted.
            string sortExpression = ViewState["ProductList_SortExpression"] as string;

            if (sortExpression != null)
            {
                // Check if the same column is being sorted. Otherwise, the default value can be returned.
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["ProductList_SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }

            // Save new values in ViewState.
            ViewState["ProductList_SortDirection"] = sortDirection;
            ViewState["ProductList_SortExpression"] = column;

            return sortDirection;
        }

        //private void Sorting(string SortExpression, string SortDirection)
        //{
        //    //string column = "";
        //    //string direction = GetSortDirection(column);
        //    //SortOrdersGridView(column, direction);
        //    //SortOrdersGridView(e.SortExpression, e.SortDirection);

        //    string direction = SortDirection.ToString().Substring(0, 3).ToLower();
        //    string column = SortExpression.ToString();
        //    try
        //    {
        //        if (Session["ProductList_" + column].ToString() == direction) Session["ProductList_" + column] = "desc";
        //        else Session["ProductList_" + column] = "asc";
        //    }
        //    catch (Exception)
        //    {
        //        Session["ProductList_" + column] = "asc";
        //    }
        //    //SortProductsGridView(column, Session["ProductList_" + column].ToString());
        //}
        //private void SortProductsGridView(string sortExpression, string direction)
        //{
        //    var orders = GetOrders(sortExpression, direction);
        //    Orders.DataSource = orders;
        //    Orders.DataBind();
        //}


        protected void gvMaster_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var client = new ProductsClient();
            int productId = (int)e.Keys[0];
            try
            {
                client.DeleteProduct(UserPrincipal.Current.UserId, productId);
                Response.Redirect("~/Admin/Products.aspx", true);
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
                e.Cancel = true;
                return;
            }
            catch (System.Exception exp)
            {
                //ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('Ошибка удаления : " + exp.Message + "');", true);
                
                //string message = string.Format("Ошибка удаления: <br />{0}", ExceptionHelper.GetAllMessage(exp));
                //this.ErrorMessage.Text = message;

                e.Cancel = true;
                return;
            }
            //ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('Товар успешно удален.');", true);
        }

        protected void gvMaster_SelectedIndexChanged(object sender, EventArgs e)
        {
        }
        
        protected void gvMaster_PageIndexChanged(object sender, EventArgs e)
        {
        }

        protected void gvMaster_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        {
            //ScriptManager.RegisterStartupScript(Page, GetType(), Guid.NewGuid().ToString(), "alert('Category successfully updated.');", true);
        }

        protected void gvMaster_Sorted(object sender, EventArgs e)
        {
        }

        protected void gvMaster_AddRow(object sender)
        {
            //_hfSearch.Value = "1 = 2";
            //BindData();
        }

        protected void gvMaster_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //if (e.CommandName == "InsertNew")
            //{
            //    TextBox tbCatName = (TextBox)gvMaster.Controls[0].Controls[0].FindControl("tbCategoryName");
            //    TextBox tbDesc = (TextBox)gvMaster.Controls[0].Controls[0].FindControl("tbDescription");
            //    TextBox tbPictureUrl = (TextBox)gvMaster.Controls[0].Controls[0].FindControl("tbPictureUrl");

            //    if (tbCatName != null)
            //        dsMaster.InsertParameters["categoryName"].DefaultValue = tbCatName.Text;
            //    if (tbDesc != null)
            //        dsMaster.InsertParameters["description"].DefaultValue = tbDesc.Text;
            //    if (tbPictureUrl != null)
            //        dsMaster.InsertParameters["pictureurl"].DefaultValue = tbPictureUrl.Text;
            //    dsMaster.Insert();
            //    _hfSearch.Value = "";
            //    BindData();
            //}
            //if (e.CommandName == "InsertCancel")
            //{
            //    _hfSearch.Value = "";
            //    BindData();
            //}
        }

        protected void gvMaster_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
        //    //if (gvMaster.Rows[e.NewSelectedIndex].FindControl("pnlChild") != null)
        //    //    gvMaster.Rows[e.NewSelectedIndex].FindControl("pnlChild").Visible = !gvMaster.Rows[e.NewSelectedIndex].FindControl("pnlChild").Visible;
        }

        protected void gvMaster_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var dataItem = e.Row.DataItem as ProductEntity;
                if (dataItem != null)
                {
                    if (e.Row.RowIndex == this.gvMaster.EditIndex)
                    {
                        var ddlMeasureUnits = e.Row.FindControl("ddlMeasureUnits") as DropDownList;
                        if (ddlMeasureUnits != null)
                        {
                            MeasureUnitsBind(ddlMeasureUnits);
                            ddlMeasureUnits.SelectedValue = dataItem.MeasureUnit.ShortName;
                        }
                    }

                    var hlBigImage = e.Row.FindControl("hlBigImage") as HyperLink;
                    if (hlBigImage != null && !string.IsNullOrEmpty(dataItem.Product.ImageBigUrl)) 
                        hlBigImage.NavigateUrl = (dataItem.Product.ImageBigUrl[0] != '~') ? string.Format("~{0}", dataItem.Product.ImageBigUrl) : dataItem.Product.ImageBigUrl;

                    var SmallImage = e.Row.FindControl("SmallImage") as Image;
                    if (SmallImage != null && !string.IsNullOrEmpty(dataItem.Product.ImageSmallUrl))
                        SmallImage.ImageUrl = (dataItem.Product.ImageSmallUrl[0] != '~') ? string.Format("~{0}", dataItem.Product.ImageSmallUrl) : dataItem.Product.ImageSmallUrl;
                }

                //var bgarr = Array("White", "#DdDdDd", "#6b8cbe", "red");

                e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='#6b8cbe'";
                e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='white'";
                //e.Row.Attributes["style"] = "cursor:hand;";

                var ri = e.Row.FindControl("ReloadImage") as HyperLink;
                if (ri != null)
                    ri.Attributes["onclick"] = string.Format("javascript: reload_image({0}, '{1}', '{2}'); return false;", dataItem.Product.ProductId, dataItem.Product.ImageBigUrl, dataItem.Product.ImageSmallUrl);

                //var grid = sender as SamApp.WebControls.NestableGridView;
                //string postback = Page.ClientScript.GetPostBackEventReference(grid, string.Format("Select${0}", e.Row.RowIndex));
                //e.Row.Attributes.Add("onclick", postback.ToString());

                if (dataItem != null)
                {
                    // Click to highlight row
                    ImageButton button = e.Row.FindControl("CloneProduct") as ImageButton;
                    if (button != null)
                    {
                        string command = "";
                        //ProductArtikul, ProductName, SupplierArtikul, SupplierName, Price
                        command = String.Format("javascript: FillFieldsNewProduct('{0}', '{1}', '{2}', '{3}', '{4}');return false;",
                            dataItem.Product.Artikul, dataItem.Product.ProductName, dataItem.Product.SupplierArtikul, dataItem.Product.SupplierName, dataItem.Product.Price);
                        button.Attributes.Add("onclick", command);
                    }
                }
            }
        }

        protected void gvMaster_RowEditing(object sender, GridViewEditEventArgs e)
        {
            //Set the edit index.
            this.gvMaster.EditIndex = e.NewEditIndex;

            //Bind data to the GridView control.
            //BindData();
            BindAndFillFiltersPaging();
        }

        protected void gvMaster_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            //Reset the edit index.
            gvMaster.EditIndex = -1;

            //Bind data to the GridView control.
            //BindData();
            BindAndFillFiltersPaging();
        }

        protected void gvMaster_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            //(gvMaster.Rows[e.RowIndex].FindControl("ddlMeasureUnits") as DropDownList).SelectedItem.Value
            var ddlMeasureUnits = gvMaster.Rows[e.RowIndex].FindControl("ddlMeasureUnits") as DropDownList;
            var txtArtikul = gvMaster.Rows[e.RowIndex].FindControl("txtArtikul") as TextBox;
            var txtPrice = gvMaster.Rows[e.RowIndex].FindControl("txtPrice") as TextBox;
            var txtProductName = gvMaster.Rows[e.RowIndex].FindControl("txtProductName") as TextBox;
            var txtSupplierArtikul = gvMaster.Rows[e.RowIndex].FindControl("txtSupplierArtikul") as TextBox;
            var txtSupplierName = gvMaster.Rows[e.RowIndex].FindControl("txtSupplierName") as TextBox;
            var cbHidden = gvMaster.Rows[e.RowIndex].FindControl("cbHidden") as CheckBox;

            int? measureUnitId = (ddlMeasureUnits != null) ? Convert.ToInt32(ddlMeasureUnits.SelectedItem.Value) : (int?)null;
            string artikul = (txtArtikul != null) ? txtArtikul.Text : "";
            double? price = (txtPrice != null && !string.IsNullOrEmpty(txtPrice.Text)) ? txtPrice.Text.GetDoubleFromString() : (double?)null;
            string productName = (txtProductName != null) ? txtProductName.Text : "";
            string supplierArtikul = (txtSupplierArtikul != null) ? txtSupplierArtikul.Text : "";
            string supplierName = (txtSupplierName != null) ? txtSupplierName.Text : "";
            bool hidden = (cbHidden != null) ? cbHidden.Checked : false;

            
            var client = new ProductsClient();

            var measureUnit = (measureUnitId.HasValue) ? client.GetMeasureUnitById(UserPrincipal.Current.UserId, measureUnitId.Value) : null;
            if (measureUnit == null)
                measureUnit = client.GetMeasureUnitById(UserPrincipal.Current.UserId, Convert.ToInt32(ConfigurationManager.AppSettings["DefaultMeasureUnitId"]));

            try
            {
                var product = new ProductEntity()
                {
                    Product = new DataTier.Product()
                    {
                        Artikul = artikul,
                        //ImageBigUrl
                        //ImageSmallUrl
                        Price = price,
                        ProductId = e.Keys["ProductId"] != null ? Convert.ToInt32(e.Keys["ProductId"]) : 0,
                        ProductName = productName,
                        SupplierArtikul = supplierArtikul,
                        SupplierName = supplierName,
                        IsHidden = hidden
                    },
                    // TODO: Сделать заполнение значения Единицы измерения
                    MeasureUnit = measureUnit
                };
                #region //Old version
                //var product = new ProductsServRef.ProductEntity()
                //{
                //    Product = new ProductsServRef.Product()
                //    {
                //        Artikul = e.NewValues["Artikul"] != null ? e.NewValues["Artikul"].ToString() : "",
                //        //ImageBigUrl
                //        //ImageSmallUrl
                //        Price = e.NewValues["Price"] != null ? e.NewValues["Price"].ToString().GetDoubleFromString() : (double?)null,
                //        ProductId = e.Keys["ProductId"] != null ? Convert.ToInt32(e.Keys["ProductId"]) : 0,
                //        ProductName = e.NewValues["ProductName"] != null ? e.NewValues["ProductName"].ToString() : "",
                //        SupplierArtikul = e.NewValues["SupplierArtikul"] != null ? e.NewValues["SupplierArtikul"].ToString() : "",
                //        SupplierName = e.NewValues["SupplierName"] != null ? e.NewValues["SupplierName"].ToString() : "",
                //        IsHidden = e.NewValues["IsHidden"] != null ? Convert.ToBoolean(e.NewValues["IsHidden"]) : false
                //    }
                //    // TODO: Сделать заполнение значения Единицы измерения
                //    //MeasureUnit = new ProductsServRef.MeasureUnit()
                //};
                #endregion //Old version

                // Сохранить запись в БД и перебиндить таблицу
                client.SaveProduct(UserPrincipal.Current.UserId, product);

                //Reset the edit index.
                gvMaster.EditIndex = -1;

                //Bind data to the GridView control.
                //BindData();
                BindAndFillFiltersPaging();
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
                e.Cancel = true;
                return;
            }
            catch (System.Exception exp)
            {
                //ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('Ошибка удаления : " + exp.Message + "');", true);

                //string message = string.Format("Ошибка удаления: <br />{0}", ExceptionHelper.GetAllMessage(exp));
                //this.ErrorMessage.Text = message;

                this.ErrorMessage.Text = exp.Message;
                e.Cancel = true;
                return;
            }
        }

        #endregion Блок кода для NestedGridView


        protected void cbHidden_CheckedChanged(object sender, EventArgs e)
        {
            var client = new ProductsClient();
            try
            {
                var checkBox = sender as CheckBox;
                int productId = Convert.ToInt32(checkBox.ToolTip);
                if (checkBox != null)
                {
                    bool isHidden = checkBox.Checked;
                    client.SetIsHidden(UserPrincipal.Current.UserId, productId, isHidden);

                    //Bind data to the GridView control.
                    //BindData();
                    BindAndFillFiltersPaging();
                }
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
                return;
            }
            catch (System.Exception exp)
            {
                this.ErrorMessage.Text = exp.Message;
                return;
            }
        }


        private void BindAndFillFiltersPaging()
        {
            SearchParameters searchParameters = null;
            searchParameters = GetSearchParameters();
            BindPaging(searchParameters);
            BindData();
            FillFiltersFields();
        }



        #region методы экспорта в Эксель

        private ExcelDocument prepareDocument()
        {
            var doc = new ExcelDocument();

            WindowProperties wp = new WindowProperties()
            {
                WindowHeight = 12015,
                WindowWidth = 19440,
                WindowTopX = 480,
                WindowTopY = 150
            };

            DocumentProperties dp = new DocumentProperties()
            {
                Author = "",
                LastAuthor = "",
                Company = "Компания МЕГА",
                Version = 1.00
            };

            doc.Header = new ExcelHeader()
            {
                WindowProperties = wp,
                DocumentProperties = dp
            };

            var workSheet = new Worksheet()
            {
                Name = "Товары",
                Table = new Common.Export.Table()
            };


            doc.Worksheets.Add(workSheet);

            return doc;
        }


        /// <summary>
        /// Создание стилей для оформления документа
        /// </summary>
        /// <param name="doc"></param>
        protected void createStyles(ExcelDocument doc)
        {
            var styleBold = new CellStyle()
            {
                ID = "bold",
                Borders = new Thickness(1),
                FontSize = 10,
                FontWeight = FontWeights.Bold,
                TextWrapping = TextWrapping.Wrap,
                FontStyle = FontStyles.Normal,
                FontFamily = new FontFamily("Arial")
            };
            var style = new CellStyle()
            {
                ID = "normal",
                Borders = new Thickness(1, 1, 1, 1),
                FontSize = 9,
                FontWeight = FontWeights.Normal,
                TextWrapping = TextWrapping.Wrap,
                FontStyle = FontStyles.Normal,
                FontFamily = new FontFamily("Arial")
            };
            var styleNumber = new CellStyle()
            {
                ID = "normalNumber",
                Borders = new Thickness(1, 1, 1, 1),
                FontSize = 9,
                FontWeight = FontWeights.Normal,
                TextWrapping = TextWrapping.Wrap,
                FontStyle = FontStyles.Normal,
                NumberFormat = "Standard",
                HorizontalAlignment = HorizontalAlignment.Right,
                FontFamily = new FontFamily("Arial")
            };
            var boldCenterHeadFoot = new CellStyle()
            {
                ID = "boldCenterHeadFoot",
                Borders = new Thickness(1),
                FontSize = 10,
                FontWeight = FontWeights.Bold,
                TextWrapping = TextWrapping.Wrap,
                FontStyle = FontStyles.Normal,
                HorizontalAlignment = HorizontalAlignment.Center,
                FontFamily = new FontFamily("Arial")
            };
            var normalCenter = new CellStyle()
            {
                ID = "normalCenter",
                Borders = new Thickness(1, 1, 1, 1),
                FontSize = 9,
                FontWeight = FontWeights.Normal,
                TextWrapping = TextWrapping.Wrap,
                FontStyle = FontStyles.Normal,
                HorizontalAlignment = HorizontalAlignment.Center,
                FontFamily = new FontFamily("Arial")
            };
            var boldCenterRight = new CellStyle()
            {
                ID = "boldCenterRight",
                Borders = new Thickness(1, 1, 1, 1),
                FontSize = 10,
                FontWeight = FontWeights.Bold,
                TextWrapping = TextWrapping.Wrap,
                FontStyle = FontStyles.Normal,
                HorizontalAlignment = HorizontalAlignment.Center,
                FontFamily = new FontFamily("Arial")
            };

            doc.Styles.Add(styleBold);
            doc.Styles.Add(style);
            doc.Styles.Add(styleNumber);
            doc.Styles.Add(boldCenterHeadFoot);
            doc.Styles.Add(boldCenterRight);
            doc.Styles.Add(normalCenter);
        }


        /// <summary>
        /// Оформление документа созданными стилями
        /// </summary>
        /// <param name="doc"></param>
        protected void setStyles(ExcelDocument doc)
        {
            var tbl = doc.Worksheets[0].Table;

            tbl.HeaderRows.ForEach(row => row.Cells.ForEach(cell => cell.StyleID = "boldCenterHeadFoot"));
            tbl.Rows.ForEach(row => row.Cells.ForEach(cell => cell.StyleID = "normal"));

            for (int i = 0; i < tbl.Rows.Count; ++i)
            {
                tbl.Rows[i].Cells[0].StyleID = "normalCenter";
                tbl.Rows[i].Cells[1].StyleID = "normal";
                tbl.Rows[i].Cells[2].StyleID = "normal";
                tbl.Rows[i].Cells[3].StyleID = "normalNumber";
                tbl.Rows[i].Cells[4].StyleID = "normal";
                tbl.Rows[i].Cells[5].StyleID = "normal";
                tbl.Rows[i].Cells[6].StyleID = "normalCenter";

                //for (int j = 1; j < tbl.Columns.Count - 1; ++j)
                //{
                //    tbl.Rows[i].Cells[j].StyleID = "normalCenter";
                //}
                //tbl.Rows[i].Cells[tbl.Columns.Count - 1].StyleID = "boldCenterRight";
            }

            //tbl.Rows[tbl.Rows.Count - 1].Cells[0].StyleID = "bold";
            //for (int i = 1; i < tbl.Columns.Count; ++i)
            //{
            //    tbl.Rows[tbl.Rows.Count - 1].Cells[i].StyleID = "boldCenterHeadFoot";
            //}
        }


        /// <summary>
        /// Создание столбцов и заголовков формируемого файла
        /// </summary>
        /// <param name="table"></param>
        /// <param name="data"></param>
        protected void createExcelColumnsAndHeaders(Common.Export.Table table)
        {
            int index = 1;
            table.Columns.Add(new Column() { AutoFitWidth = 1, Width = 80.0, Index = index++ });
            table.Columns.Add(new Column() { AutoFitWidth = 1, Width = 100.0, Index = index++ });
            table.Columns.Add(new Column() { AutoFitWidth = 1, Width = 300.0, Index = index++ });
            table.Columns.Add(new Column() { AutoFitWidth = 1, Width = 100.0, Index = index++ });
            table.Columns.Add(new Column() { AutoFitWidth = 1, Width = 140.0, Index = index++ });
            table.Columns.Add(new Column() { AutoFitWidth = 1, Width = 200.0, Index = index++ });
            table.Columns.Add(new Column() { AutoFitWidth = 1, Width = 150.0, Index = index++ });

            var headerrow = new Row();
            headerrow.Cells.Add(new Cell() { Data = "ID товара" });
            headerrow.Cells.Add(new Cell() { Data = "Артикул товара" });
            headerrow.Cells.Add(new Cell() { Data = "Наименование товара" });
            headerrow.Cells.Add(new Cell() { Data = "Цена товара" });
            headerrow.Cells.Add(new Cell() { Data = "Артикул у поставщика" });
            headerrow.Cells.Add(new Cell() { Data = "Наименование у поставщика" });
            headerrow.Cells.Add(new Cell() { Data = "Видимый пользователям" });
            table.HeaderRows.Add(headerrow);
        }


        /// <summary>
        /// Заполнение документа данными
        /// </summary>
        /// <param name="table"></param>
        /// <param name="data"></param>
        protected void appendExcelData(Common.Export.Table table, List<ProductEntity> data)
        {
            table.Rows.AddRange(data.Select(row =>
            {
                var result = new Row();
                result.Cells.Add(new Cell() { Data = row.Product.ProductId.ToString(), Type = "Number" });
                result.Cells.Add(new Cell() { Data = row.Product.Artikul, Type = "String" });
                result.Cells.Add(new Cell() { Data = row.Product.ProductName, Type = "String" });
                result.Cells.Add(new Cell() { Data = row.Product.Price.ToString().Replace(",", "."), Type = "Number" });
                result.Cells.Add(new Cell() { Data = row.Product.SupplierArtikul, Type = "String" });
                result.Cells.Add(new Cell() { Data = row.Product.SupplierName, Type = "String" });
                result.Cells.Add(new Cell() { Data = (row.Product.IsHidden) ? "скрытый" : "видимый", Type = "String" });

                return result;
            }).ToArray());
        }


        protected void btnToExcelAllList_Click(object sender, EventArgs e)
        {
                var client = new ProductsClient();
                try
                {
                    // Узнаем список товаров 
                    var products = client.GetProductList(UserPrincipal.Current.UserId, 1, 100000000);
                    if (products != null && products.Count > 0)
                    {
                        var doc = prepareDocument();

                        createStyles(doc);
                        createExcelColumnsAndHeaders(doc.Worksheets[0].Table);
                        appendExcelData(doc.Worksheets[0].Table, products);
                        setStyles(doc);

                        Response.Redirect(string.Format("~/ExcelReport.ashx?FileName={0}&ReportID={1}",
                                                        "Товары",
                                                        ExcelLoader.SaveReport(Context, Guid.NewGuid(), doc.ToString())));
                    }
                }
                catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
                {
                    string message = client.GetExceptionDetail(ex);
                    this.ErrorMessage.Text = message;
                }
                catch (System.Exception exp)
                {
                    this.ErrorMessage.Text = exp.Message;
                }
        }

        #endregion методы экспорта в Эксель

    }
}